from machine import Pin
from micropython import const

import time

from devices import *
from ui import *
from pyb import Timer
from pyb import LED

SHORT_ON	= const(4000)
LONG_ON		= const(120000)

class Input:
	def Init():
		Input.button = Pin('X1', Pin.IN, Pin. PULL_UP)
		Input.led_blue = LED(4)
		Input.check_ticks_ms = 0
		Input.buttonDown = 0
		Input.buttonUp = 0
		Input.OnTime = 0

	def TurnOnSubLed(on):
		Devices.Sub_led_switch(on)
		UI.SetSubLed(on)

	def Button_Clck():
		# delay off (short)
		# if on:
		if UI.Sub_led:
			Input.TurnOnSubLed(False)
			Input.OnTime = 0
		else:
			Input.TurnOnSubLed(True)
			Input.OnTime = SHORT_ON

		return

	def Button_Long_Press():
        # delay off (long)
		Input.TurnOnSubLed(True)
		Input.OnTime = LONG_ON
		return

	def Check():
		t = time.ticks_ms()
		if time.ticks_diff(t, Input.check_ticks_ms) < 5:
			return
		else:
			Input.check_ticks_ms = t

		if Input.OnTime > 0:
			Input.OnTime -= 1
			if Input.OnTime == 0:
				Input.TurnOnSubLed(False)

		v = Input.button.value()
		if v == 0:
			# Button push down
			Input.buttonDown += 1
			Input.buttonUp = 0
			if Input.buttonDown >= 400:
				Input.led_blue.on()
		else:
			Input.buttonUp += 1
			if Input.buttonUp <= 2:
				return
				
			if Input.buttonDown >= 400:
				# Long press
				Input.Button_Long_Press()
			elif Input.buttonDown >= 4:
				# Click
				Input.Button_Clck()
			# else:
				# Nothing
			
			Input.buttonDown = 0
			Input.buttonUp = 0
			Input.led_blue.off()



